package org.ktx.osr.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewConfiguration
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.TextView
import org.ktx.osr.R
import kotlin.math.abs

/**
 * 音视频处理进度浮窗组件
 */
@SuppressLint("ClickableViewAccessibility")
class ProcessingProgressWidget @JvmOverloads constructor(
    context: Context, 
    attrs: AttributeSet? = null, 
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val root = LayoutInflater.from(context).inflate(R.layout.processing_progress_widget, this, true)
    private val titleText: TextView = root.findViewById(R.id.tv_title)
    private val currentTaskText: TextView = root.findViewById(R.id.tv_current_task)
    private val progressBar: ProgressBar = root.findViewById(R.id.progress_bar)
    private val progressText: TextView = root.findViewById(R.id.tv_progress)
    private val statusText: TextView = root.findViewById(R.id.tv_status)
    
    private val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
    private var lastX: Float = 0f
    private var lastY: Float = 0f
    private var firstX: Int = 0
    private var firstY: Int = 0
    private var isDragging = false
    
    init {
        setupTouchListener()
        updateVisibility(false)
    }
    
    /**
     * 设置触摸监听器，支持拖拽
     */
    private fun setupTouchListener() {
        setOnTouchListener { _, event ->
            when (event.action) {
                android.view.MotionEvent.ACTION_DOWN -> {
                    lastX = event.rawX
                    lastY = event.rawY
                    firstX = (layoutParams as WindowManager.LayoutParams).x
                    firstY = (layoutParams as WindowManager.LayoutParams).y
                    isDragging = false
                }
                
                android.view.MotionEvent.ACTION_MOVE -> {
                    val dx = event.rawX - lastX
                    val dy = event.rawY - lastY
                    if (abs(dx) > touchSlop || abs(dy) > touchSlop) {
                        isDragging = true
                    }
                    if (isDragging) {
                        val params = layoutParams as WindowManager.LayoutParams
                        params.x = firstX + (event.rawX - lastX).toInt()
                        params.y = firstY + (event.rawY - lastY).toInt()
                        windowManager.updateViewLayout(this, params)
                    }
                }
                
                android.view.MotionEvent.ACTION_UP -> {
                    if (!isDragging) {
                        performClick()
                    }
                }
            }
            true
        }
    }
    
    /**
     * 更新任务信息
     * @param currentTaskIndex 当前任务索引（从1开始）
     * @param totalTasks 总任务数
     * @param taskDescription 当前任务描述
     */
    fun updateTaskInfo(currentTaskIndex: Int, totalTasks: Int, taskDescription: String) {
        titleText.text = "音视频处理进度 ($currentTaskIndex/$totalTasks)"
        currentTaskText.text = taskDescription
    }
    
    /**
     * 更新进度
     * @param progress 进度百分比 (0-100)
     * @param status 状态描述
     */
    fun updateProgress(progress: Int, status: String = "") {
        val clampedProgress = progress.coerceIn(0, 100)
        progressBar.progress = clampedProgress
        progressText.text = "$clampedProgress%"
        
        if (status.isNotEmpty()) {
            statusText.text = status
        }
    }
    
    /**
     * 更新状态文本
     */
    fun updateStatus(status: String) {
        statusText.text = status
    }
    
    /**
     * 显示浮窗
     */
    fun show() {
        updateVisibility(true)
    }
    
    /**
     * 隐藏浮窗
     */
    fun hide() {
        updateVisibility(false)
    }
    
    /**
     * 更新可见性
     */
    private fun updateVisibility(visible: Boolean) {
        visibility = if (visible) VISIBLE else GONE
    }
    
    /**
     * 创建窗口布局参数
     */
    fun createLayoutParams(): WindowManager.LayoutParams {
        val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            @Suppress("DEPRECATION")
            WindowManager.LayoutParams.TYPE_PHONE
        }
        
        return WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            type,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.END
            x = 50
            y = 200
        }
    }
    
    /**
     * 重置进度
     */
    fun resetProgress() {
        progressBar.progress = 0
        progressText.text = "0%"
        statusText.text = "准备中..."
    }
    
    /**
     * 设置完成状态
     */
    fun setCompleted() {
        progressBar.progress = 100
        progressText.text = "100%"
        statusText.text = "处理完成"
    }
    
    /**
     * 设置错误状态
     */
    fun setError(errorMessage: String) {
        statusText.text = "错误: $errorMessage"
    }
}
